package com.fcc.wfly.common.service.impl;

import com.fcc.wfly.common.dao.CommonDao;
import com.fcc.wfly.common.domain.RestApiRequestTrack;
import com.fcc.wfly.common.service.CommonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

@Service("commonService")
public class CommonServiceImpl implements CommonService {

	@Autowired
	private CommonDao commonDao;

	public void addRequestLog(RestApiRequestTrack restApiRequestTrack) {
		commonDao.addRequestLog(restApiRequestTrack);
	}

	private ReadWriteLock seriesCacheLock = new ReentrantReadWriteLock();
	private static Map<String, String> seriesCache = new HashMap<String, String>();

	public String getSeriesByPn(String pn) {
		seriesCacheLock.readLock().lock();
		String series = seriesCache.get(pn);
		seriesCacheLock.readLock().unlock();
		if (series == null) {
			seriesCacheLock.writeLock().lock();
			if (series == null) {
				series = commonDao.getSeriesByPn(pn);
				seriesCache.put(pn, series==null?"":series);
			}
			seriesCacheLock.writeLock().unlock();
		}
		Assert.isTrue(StringUtils.hasText(series), "Don't find the PN[" + pn + "] series");
		return series;
	}

}